package com.lemon.smartsafety.rayeye;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.gson.Gson;
import com.ldzs.recyclerlibrary.Mode;
import com.ldzs.recyclerlibrary.PullToRefreshRecyclerView;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.listener.RecyclerTClickListener;
import com.lemon.smartsafety.rayeye.adapter.FFListAdapter;
import com.lemon.smartsafety.rayeye.entity.BundleKey;
import com.lemon.smartsafety.rayeye.entity.FaultFireListI;
import com.lemon.smartsafety.rayeye.entity.FireListVo;
import com.lemon.smartsafety.rayeye.entity.FireVo;
import com.lemon.smartsafety.rayeye.util.RayType;
import com.lemon.smartsafety.rayeye.util.TypeUtils;
import com.lemon.smartsafety.rayeye.util.Urls;
import com.lemon.smartsafetynew.ui.fragment.base.BaseFragment;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.view.list.MultiStateView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Cooliean on 16/4/16.
 */
public class FireListFragment extends BaseFragment {
    private LoggerHelper loggerHelper = new LoggerHelper(FireListFragment.class);

    @Bind(R.id.pullToRefreshRecyclerView)
    PullToRefreshRecyclerView pullToRefreshRecyclerView;
    @Bind(R.id.multiStateView)
    MultiStateView            multiStateView;
    private int pageSize    = 30;
    private int currentPage = 1;

    FFListAdapter mAdapter;
    List<FaultFireListI> items = new ArrayList<>();

    private Activity mContext;


    private FireListVo mFireListVo;
    private RayType.ListType mType = RayType.ListType.FIRE;

    private int mListType = 0;
    private int mBuildId  = 0;

    private String sUrl = "";
    private String mCompanyCode = "";

    private LinearLayoutManager mLayoutManager;

    public static FireListFragment newInstance(String companyCode,int buildId, int typeId) {
        Bundle bundle = new Bundle();
        bundle.putInt(BundleKey.BUILDING_ID, buildId);
        bundle.putInt(BundleKey.FIRE_TYPE_ID, typeId);
        bundle.putString(BundleKey.COMPANY_CODE, companyCode);
        FireListFragment fragment = new FireListFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void getBaseArguments() {
        if (getArguments() != null) {
            mCompanyCode = getArguments().getString(BundleKey.COMPANY_CODE, "");
            mBuildId = getArguments().getInt(BundleKey.BUILDING_ID, 0);
            mListType = getArguments().getInt(BundleKey.FIRE_TYPE_ID, 0);
        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_refresh_no_title;
    }

    @Override
    protected void initViews() {
        sUrl = String.format(Urls.GET_FIRE_LIST, mSharedPreferencesHelper.getRayEyeUrl());
        mContext = getActivity();
        multiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
        multiStateView.setRetryListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                multiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                pullToRefreshRecyclerView.beginRefreshing();
            }
        });
        mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);


        mAdapter = new FFListAdapter(items, new RecyclerTClickListener<FaultFireListI>() {
            @Override
            public void onItemClick(FaultFireListI data, int position) {
                Bundle bundle = new Bundle();
                bundle.putInt(BundleKey.BUILDING_ID, mBuildId);
                bundle.putSerializable(BundleKey.TYPE, (Serializable) data.getDescType());
                bundle.putInt(BundleKey.V_ID, data.getValueIdI());
                bundle.putString(BundleKey.COMPANY_CODE, mCompanyCode);
                UIHelper.showActivity(mContext, bundle, FireDetailActivity.class);
            }
        });

        pullToRefreshRecyclerView.setLayoutManager(mLayoutManager);
        pullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
        pullToRefreshRecyclerView.setAdapter(mAdapter);
        pullToRefreshRecyclerView.setOnPullUpToRefreshListener(new PullToRefreshRecyclerView.OnPullUpToRefreshListener() {
            @Override
            public void onRefresh() {
                currentPage = 1;
                getNetData();
            }
        });
        pullToRefreshRecyclerView.setOnPullDownToRefreshListener(new PullToRefreshRecyclerView.OnPullDownToRefreshListener() {
            @Override
            public void onRefresh() {
                getNetData();
            }
        });
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        pullToRefreshRecyclerView.beginRefreshing();
    }

    private void getNetData() {
        LemonRequestParams params = new LemonRequestParams();
        params.put("code", mCompanyCode);
        params.put("key", Urls.APP_FIRE_SUPERVISON_KEY);
        params.put("limit", pageSize);
        params.put("page", currentPage);
        params.put("bid", mBuildId);
        params.put("type", mListType);

        OkHttpUtils.post()
                   .url(sUrl)
                   .tag(sUrl)
                   .params(params)
                   .build()
                   .execute(new Callback<FireListVo>() {
                       @Override
                       public void onBefore(Request request) {
                           super.onBefore(request);
                           //mHUDUtil.showHUD();
                       }

                       @Override
                       public FireListVo parseNetworkResponse(Response response) throws Exception {
                           String result = response.body().string();
                           //loggerHelper.w(result);
                           return new Gson().fromJson(result, getType());
                       }

                       @Override
                       public void onError(Call call, Exception e) {
                           e.printStackTrace();
                           if (pullToRefreshRecyclerView != null) {
                               pullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
                           }
                           if (mHUDUtil != null) {
                               mHUDUtil.hidden();
                           }
                           if (multiStateView != null) {
                               multiStateView.setErrorTip(e.getLocalizedMessage());
                           }
                       }

                       @Override
                       public void onAfter() {
                           super.onAfter();
                       }

                       @Override
                       public void onResponse(FireListVo response) {
                           if (pullToRefreshRecyclerView != null) {
                               pullToRefreshRecyclerView.onRefreshComplete();
                           }
                           if (mHUDUtil != null) {
                               mHUDUtil.hidden();
                           }
                           mFireListVo = response;
                           if (mFireListVo != null) {
                               List<FireVo> temps = mFireListVo.getListob();
                               if (temps != null && temps.size() != 0) {
                                   if (currentPage == 1) {
                                       items.clear();
                                   }
                                   for (int i = 0; i < temps.size(); i++) {
                                       temps.get(i).setBigType(mType);
                                       temps.get(i).setSmallType(TypeUtils.getTypeById(mType, mListType));
                                   }
                                   items.addAll(temps);
                                   if (mAdapter != null) {
                                       mAdapter.notifyDataSetChanged();
                                   }
                               }else{
                                   if (mFireListVo.getPagetotal() == 0 && mFireListVo.getNopage() == 1 && multiStateView != null) {
                                       multiStateView.setEmptyTip("没有相关记录");
                                   }
                               }

                               if (pullToRefreshRecyclerView != null) {
                                   if (mFireListVo.isHasNextPage()) {
                                       currentPage++;
                                       pullToRefreshRecyclerView.setRefreshMode(Mode.BOTH);
                                   } else {
                                       pullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
                                   }
                               }

                           } else {
                               if (pullToRefreshRecyclerView != null) {
                                   pullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
                               }
                           }
                       }
                   });
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
